package com.retry.task.admin.infrastructure.lock;

import com.google.common.collect.Maps;
import com.retry.task.admin.constants.LockStatusEnum;
import com.retry.task.admin.dal.mapper.RetryTaskLockMapper;
import com.retry.task.admin.dal.model.RetryTaskLockDO;
import com.retry.task.core.utils.CommonExecuteUtils;
import com.retry.task.core.utils.IpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/5/9  10:30
 * @Description TODO
 */
@Service
public class MysqlLockServiceImpl implements ILock {

    @Autowired
    private RetryTaskLockMapper retryTaskLockMapper;

    @Override
    @Transactional
    public boolean tryLock(String key, Integer isTest) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if (isTest == null) {
            return false;
        }
        Map<String, Object> params = Maps.newHashMap();
        params.put("lockName", key);
        params.put("isTest", isTest);
        params.put("lockStatus", LockStatusEnum.NO_LOCK.getStatus());
        RetryTaskLockDO retryTaskLockDO = retryTaskLockMapper.getProjectLock(params);
        if (retryTaskLockDO == null) {
            return false;
        }
        retryTaskLockDO.setLockStatus(LockStatusEnum.LOCKING.getStatus());
        retryTaskLockDO.setCurrentLockIp(IpUtils.getIp());
        retryTaskLockDO.setCurrentLockTime(new Date());
        retryTaskLockMapper.updateByPrimaryKey(retryTaskLockDO);
        return true;
    }

    @Override
    public boolean tryLockWithWait(String key, Integer isTest, Integer waitTime) {
        return false;
    }

    @Override
    public int releasLock(String key, Integer isTest) {
        if (StringUtils.isEmpty(key)) {
            return -1;
        }
        if (isTest == null) {
            return -1;
        }
        RetryTaskLockDO retryTaskLockDO = new RetryTaskLockDO();
        retryTaskLockDO.setLockName(key);
        retryTaskLockDO.setIsTest(isTest);
        retryTaskLockDO.setLockStatus(LockStatusEnum.NO_LOCK.getStatus());
        Map<String, Object> paramMap = CommonExecuteUtils.beanToMap(retryTaskLockDO, false);
        return retryTaskLockMapper.releaseLock(paramMap);
    }
}
